package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpServletRequest req;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.anno.Log)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //开始执行时间戳
        long begin = System.currentTimeMillis();
        //登录员工的ID（token解析出来id）
        String token = req.getHeader("Token");
        Claims body = Jwts.parser()
                .setSigningKey("itheima".getBytes())
                .parseClaimsJws(token)
                .getBody();
        Integer userId = (Integer) body.get("id");
        //操作时间
        LocalDateTime now = LocalDateTime.now();
        //操作类名
        String className = pjp.getTarget().getClass().getName();
        //操作方法名
        String methodName = pjp.getSignature().getName();
        //方法参数
        Object[] args = pjp.getArgs();
        String argsStr = Arrays.toString(args);
        //原样调用
        Object result = pjp.proceed();//调用增删改方法，这些方法没有返回值，返回的其实就是null
        //方法的返回值
        String resultStr = null;
        if (result != null) {
            resultStr = result.toString();
        }
        //方法结束的时间戳
        long end = System.currentTimeMillis();
        //执行时长
        Long time = end-begin;
        //记录操作日志
        OperateLog log = new OperateLog(null, userId, now, className, methodName, argsStr, resultStr, time);
        operateLogMapper.insert(log);
        return result;
    }
}
